//
//  FeedbackViewController.m
//  EMMApp
//
//  Created by Mac on 16/6/29.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "FeedbackViewController.h"
#import "MHPhotoBrowserController.h"
#import "MHPhotoModel.h"
/** Api
 *
 *  Api调用导入.h文件
 */
#import "AddProblemFeedbackApi.h"

/** 第三方文件
 *
 *  第三方文件导入.h文件
 */
#import "NSString+Base64.h"
#import "NSData+Base64.h"
#import "QBImagePickerController.h"

/** 系统库
 *
 *  系统库导入.h文件
 */
#import <AVFoundation/AVFoundation.h>

/** Cell
 *
 *  Cell导入.h文件
 */
#import "VGReturnPartPicViewCell.h"

@interface FeedbackViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,QBImagePickerControllerDelegate,UIActionSheetDelegate>

/**
 *  反馈问题输入框
 */
@property (nonatomic, strong) UITextView *inputTextView;

/**
 *  反馈问题图片
 */
@property (nonatomic, strong) UIImageView *feedImageView;

/**
 *  选择图片数组
 */
@property(nonatomic,strong) NSMutableArray* picArray;

/**
 *  选择图片数组(bate64位数据)
 */
@property(nonatomic,strong) NSMutableArray* dataArr;//选择图片数组

/**
 *  反馈问题说明
 */
@property (nonatomic, strong) UILabel *feedbackLabel;

@end

@implementation FeedbackViewController

#pragma amrk - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    _picArray = [[NSMutableArray alloc] init];
    _dataArr = [[NSMutableArray alloc] init];
    [self creatNavigationController];
    [self creatShowUI];
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(10, EMM_HEIGHT-70-50, EMM_WIDTH-20, 50);
    [btn setTitle:@"提  交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor colorFromHexCode:@"#e97300"];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 4;
    [self.view addSubview:btn];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 提交按钮响应事件
- (void)btnClick:(UIButton *)btn {
    [self postGetCalculatePriceApi];
}

- (void)postGetCalculatePriceApi {
    [self showHud:@"正在加载请稍等..."];
    AddProblemFeedbackApi *api = [[AddProblemFeedbackApi alloc] initWithProblemContent:_inputTextView.text problemImageList:_dataArr];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        AddProblemFeedbackApi *result = (AddProblemFeedbackApi *)request;
        if (result.isSuccess) {
             [self hideHud];
            if (_feedbackBlock) {
                _feedbackBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        } else {
            [self showToast:result.resultData.errorMsg];
        }
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 导航
- (void)creatNavigationController {
    [self updateNavBar];
    self.navigationItem.title = @"反馈";
    [self configLeftBtn];
}

#pragma mark - 初始化创建界面内的控件
- (void)creatShowUI {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 270)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    UIView *v1 = [[UIView alloc] initWithFrame:CGRectMake(0, 269.5, EMM_WIDTH, 0.5)];
    v1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    [view addSubview:v1];
    
    _inputTextView = [[UITextView alloc] initWithFrame:CGRectMake(15, 5, EMM_WIDTH-30, 170)];
    _inputTextView.delegate = self;
    _inputTextView.keyboardType = UIKeyboardTypeDefault;
    _inputTextView.returnKeyType = UIReturnKeyDone;
    _inputTextView.font = [UIFont systemFontOfSize:16];
    [view addSubview:_inputTextView];
    
    _feedImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 180, 80, 80)];
    _feedImageView.image = [UIImage imageNamed:@"fyuan_img"];
    UIButton *seeImaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    seeImaButton.frame = CGRectMake(10, 180, 80, 80);
    [seeImaButton addTarget:self action:@selector(seeImaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_feedImageView];
    [view addSubview:seeImaButton];
   
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(100, 180, 80, 80)];
    imageView1.image = [UIImage imageNamed:@"btn_plus"];
    [view addSubview:imageView1];
    UIButton *btnImage = [UIButton buttonWithType:UIButtonTypeSystem];
    btnImage.frame = CGRectMake(100, 180, 80, 80);
    [btnImage addTarget:self action:@selector(btnImageClick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btnImage];
    
    _feedbackLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 7, EMM_WIDTH-40, 36)];
    _feedbackLabel.font = [UIFont systemFontOfSize:14];
    _feedbackLabel.numberOfLines = 0;
    _feedbackLabel.text = @"请写出您的宝贵意见或建议，我们会努力做更好反馈";
    _feedbackLabel.textColor = [UIColor lightGrayColor];
    [view addSubview:_feedbackLabel];
}

#pragma mark - 预览图片与删除
- (void)seeImaButtonAction:(UIButton *)sender{
    if (_picArray.count > 0) {
        MHPhotoBrowserController *vc = [MHPhotoBrowserController new];
        NSMutableArray * bigImgArray = [NSMutableArray new];
        for (int i = 0; i < _picArray.count; i++) {
            VGReturnGoodsPicDTO *dto = [_picArray objectAtIndex:i];
            [bigImgArray addObject:[MHPhotoModel photoWithImage:dto.picImage]];
        }
        vc.currentImgIndex = 0;
        vc.displayTopPage = YES;
        vc.displayDeleteBtn = YES;
        vc.imgArray = bigImgArray;
        //删除按钮回调方法
        __block FeedbackViewController *blockSelf = self;
        [vc setMHPhotoBrowserBlock:^(NSInteger index) {
            NSLog(@"删除了第%ld张",index);
            [blockSelf.picArray removeObjectAtIndex:index];
            [blockSelf.dataArr removeObjectAtIndex:index];
            if ([_picArray count])
            {
                VGReturnGoodsPicDTO *temp = _picArray[0];
                _feedImageView.image = temp.picImage;
            }else {
                _feedImageView.image = [UIImage imageNamed:@"fyuan_img"];
            }
        }];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark - 选择图片
- (void)btnImageClick:(UIButton *)btn {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}


#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        [self showPhotosFromCamera];
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        [self showSelectPhotos];
        
    }
}

#pragma amrk - UITextView代理方法调用
- (void)textViewDidChange:(UITextView *)textView {
    _feedbackLabel.hidden = YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    _inputTextView.text = textView.text;
    if (_inputTextView.text.length > 0) {
        _feedbackLabel.hidden = YES;
    }else {
        _feedbackLabel.hidden = NO;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - 调用系统相机和相册
////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma mark camera utility

////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL) isCameraAvailable {
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable {
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) canUserPickVideosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary {
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType
{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark 1 拍照
- (void)showPhotosFromCamera {
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                           animated:YES
                         completion:^(void){
                             NSLog(@"Picker View Controller is presented");
                         }];
    } else {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>相机>Vgo\"中点击启用."];
    }
}

#pragma mark - UIImagePickerControllerDelegate
#pragma mark 2 拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self showThisImagePicker:picker info:info];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark 3 拍照
- (void)showThisImagePicker:(UIImagePickerController *)picker info:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
        if (imageData == NULL) {
            return;
        }
        NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
        NSString *encodedImageStr = base64EncodedString;
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:encodedImageStr forKey:@"problemImage"];
        [dict setObject:@".png" forKey:@"problemImageType"];
        [_dataArr addObject:dict];
        VGReturnGoodsPicDTO *v = [[VGReturnGoodsPicDTO alloc] init];
        v.picImage = portraitImg;
        [_picArray addObject:v];
        if ([_picArray count])
        {
            VGReturnGoodsPicDTO *temp = _picArray[0];
            _feedImageView.image = temp.picImage;
        }else {
            _feedImageView.image = [UIImage imageNamed:@"fyuan_img"];
        }
    }];
}

#pragma mark 照片
- (void)showSelectPhotos {
    if (![self isPhotoLibraryAvailable]) {
        [self alertWithTitle:@"无法访问相机" msg:@"在\"设置>隐私>照片>M2案场管理\"中点击启用."];
        return;
    }
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.showsNumberOfSelectedAssets = YES;
    imagePickerController.maximumNumberOfSelection = 5;
    
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}

#pragma mark - QBImagePickerControllerDelegate
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
    NSLog(@"Selected assets:");
    NSLog(@"%@", assets);// addbtn100
    for (ALAsset *result in assets) {
        // ALAsset的类型
        NSString *assetType = [result valueForProperty:ALAssetPropertyType];
        if ([assetType isEqualToString:ALAssetTypePhoto]){
            ALAssetRepresentation *assetRepresentation =[result defaultRepresentation];
            //            CGFloat imageScale = [assetRepresentation scale];
            UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
            
            CGImageRef imageReference = [assetRepresentation fullResolutionImage];
            // 对找到的图片进行操作
            UIImage *image = [[UIImage alloc] initWithCGImage:imageReference scale:1.0 orientation:imageOrientation];
            if (image != nil){
                VGReturnGoodsPicDTO *v = [[VGReturnGoodsPicDTO alloc] init];
                v.picImage = image;
                v.asset = result;
                [_picArray addObject:v];
                
            } else {
                NSLog(@"Failed to create the image.");
            }
        }
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
    if ([_picArray count])
    {
        VGReturnGoodsPicDTO *temp = _picArray[0];
        _feedImageView.image = temp.picImage;
    }else {
        _feedImageView.image = [UIImage imageNamed:@"fyuan_img"];
    }
    [self cat];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)cat {
    NSMutableArray *strarr = nil;
    for (int i=0; i<_picArray.count; i++) {
        if (!strarr) {
            strarr = [NSMutableArray array];
        }
        VGReturnGoodsPicDTO *dto = [_picArray objectAtIndex:i];
        NSString *base64 = [self postImage:dto.picImage];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:base64 forKey:@"problemImage"];
        [dict setObject:@".png" forKey:@"problemImageType"];
        [_dataArr addObject:dict];
    }
}

- (NSString *)postImage:(UIImage *)portraitImg {
    NSData* imageData = UIImageJPEGRepresentation(portraitImg, 0.1);
    if (imageData == NULL) {
        return nil;
    }
    NSString *base64EncodedString = [NSString base64StringFromData:imageData length:[imageData length]];
    NSString *encodedImageStr = base64EncodedString;
    return encodedImageStr;
}

@end
